<?php
class Feedback_model extends CI_Model {
	function __construct()
    {
        parent::__construct();
    }
    /**
     * 获取举报
     * @param $target_id
     * @param $target_type
     */
	public function find_feedbacks_by_target_id($target_id, $target_type) {
		$this->db->where('target_id', intval($target_id));
		$this->db->where('target_type', $target_type);
		return $this->db->get('feedbacks')->result_array();
	}
	/**
	 * 获取举报类型
	 * @param string $type
	 */
	public function find_feedbacks_by_target_type($type) {
		$sql = "select u.nickname,u.status,f.* from feedbacks f left join users u on u.id=f.target_id 
		where f.target_type=" . $this->db->escape($type);
		return $this->db->query($sql)->result_array();
	}
	
	public function add($data) {   
		$this->db->insert("feedbacks", $data);
		return $this->db->insert_id();
	}
	
	public function delete_by_target_id($target_id, $target_type) {
		$sql = "delete from feedbacks where target_id=" . $target_id . " and target_type='". $target_type . "'";
		return $this->db->query($sql);
	}

	public function get_count_all($type) {
		$sql = "select count(distinct(e.id)) as total from feedbacks f 
			left join emergencies e on e.id=f.target_id
			left join users u on u.id = e.created_by 
			where f.target_type='" . $type . "' and e.id is not null
			 ";
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
	
	public function find_all($type, $offset = 0, $limit = 20) {
		$sql = "select u.nickname,f.created, f.type,e.id,e.created_by,e.bonus,e.title from feedbacks f 
			left join emergencies e on e.id=f.target_id
			left join users u on u.id = e.created_by 
			where f.target_type='" . $type . "' and e.id is not null
			group by e.id order by f.created desc limit " . $offset . "," . $limit;
		return $this->db->query($sql)->result_array();
	}
	
	public function find_all_story() {
		$sql = "select u.nickname,f.created, f.type,u.id,u.status,count(*) as total from feedbacks f 
			left join emergencies e on e.id=f.target_id
			left join users u on u.id = e.created_by 
			where f.target_type='story' and e.id is not null
			group by u.id";
		return $this->db->query($sql)->result_array();
	}
}